package com.lijy.vue.rest.config;

import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.module.SimpleModule;
import com.fasterxml.jackson.databind.ser.std.ToStringSerializer;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.json.Jackson2ObjectMapperBuilder;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import java.util.ArrayList;
import java.util.List;


/**
 * springboot2.4 跨域 https://www.jb51.net/article/201453.htm
 * @author slj
 */
@Configuration
public class WebAppConfig implements WebMvcConfigurer {
	@Override
	public void addCorsMappings(CorsRegistry registry) {
		//添加映射路径
		registry.addMapping("/**")
				//放行哪些原始域
				.allowedOrigins("*")
				//是否发送Cookie信息
//				.allowCredentials(true)
				//放行哪些原始域(请求方式)
				.allowedMethods("*")
				//放行哪些原始域(头部信息)
				.allowedHeaders("*")
				//暴露哪些头部信息（因为跨域访问默认不能获取全部头部信息）
				.exposedHeaders("Header1", "Header2");
	}

	private CorsConfiguration buildConfig() {
		CorsConfiguration corsConfiguration = new CorsConfiguration();
		// 1允许域名使用
		List<String> allowedOriginPatterns=new ArrayList<>();
		allowedOriginPatterns.add("*");
		allowedOriginPatterns.add("http://localhost");
		corsConfiguration.setAllowedOriginPatterns(allowedOriginPatterns);
		// 2允许任何头
		corsConfiguration.addAllowedHeader("*");
		// 3允许任何方法（post、get等）
		corsConfiguration.addAllowedMethod("*");
		corsConfiguration.setAllowCredentials(true);
		// 4.解决跨域请求两次，预检请求的有效期，单位为秒
		corsConfiguration.setMaxAge(1800L);
		return corsConfiguration;
	}

	@Bean
	public CorsFilter corsFilter() {
		UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
		source.registerCorsConfiguration("/**", buildConfig());
		return new CorsFilter(source);
	}

	@Bean
	public FilterRegistrationBean filterDemo4Registration() {
		FilterRegistrationBean registration = new FilterRegistrationBean();
		registration.setFilter(corsFilter());
		registration.addUrlPatterns("/*");
		registration.addInitParameter("paramName", "paramValue");
		registration.setName("corsFilter");
		registration.setOrder(1);
		return registration;
	}

	@Bean
	public ObjectMapper jacksonObjectMapper(Jackson2ObjectMapperBuilder builder) {
		ObjectMapper objectMapper = builder.createXmlMapper(false).build();
		//忽略value为null 时 key的输出
		objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
		/**
		 * 序列换成json时,将所有的long变成string
		 * 因为js中得数字类型不能包含所有的java long值
		 */
		SimpleModule module = new SimpleModule();
		module.addSerializer(Long.class, ToStringSerializer.instance);
		module.addSerializer(Long.TYPE, ToStringSerializer.instance);
		objectMapper.registerModule(module);
		return objectMapper;
	}

//	@Override
//	public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
//		//1.需要定义一个convert转换消息的对象;
//		FastJsonHttpMessageConverter fastJsonHttpMessageConverter = new FastJsonHttpMessageConverter();
//		//2.添加fastJson的配置信息，比如：是否要格式化返回的json数据;
//		FastJsonConfig fastJsonConfig = new FastJsonConfig();
//		fastJsonConfig.setSerializerFeatures(SerializerFeature.PrettyFormat,
//				SerializerFeature.WriteMapNullValue,
//				SerializerFeature.WriteNullStringAsEmpty,
//				SerializerFeature.DisableCircularReferenceDetect,
//				SerializerFeature.WriteNullListAsEmpty,
//				SerializerFeature.WriteDateUseDateFormat);
//		//3处理中文乱码问题
//		List<MediaType> fastMediaTypes = new ArrayList<>();
//		fastMediaTypes.add(MediaType.APPLICATION_JSON_UTF8);
//		//4.在convert中添加配置信息.
//		fastJsonHttpMessageConverter.setSupportedMediaTypes(fastMediaTypes);
//		fastJsonHttpMessageConverter.setFastJsonConfig(fastJsonConfig);
//		//5.将convert添加到converters当中.
//		converters.add(fastJsonHttpMessageConverter);
//	}
}


